// -----------------------------------------------------------------------
//  <copyright file="BeginOrUseTransactionInterceptor.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024/12/10 15:30:26</last-date>
// -----------------------------------------------------------------------

using Microsoft.EntityFrameworkCore.Diagnostics;

namespace DaprPlus.EntityFrameworkCore;

/// <summary>
/// 开启或使用事务拦截器
/// </summary>
public class BeginOrUseTransactionInterceptor(IServiceProvider provider) : SaveChangesInterceptor
{
    public override int SavedChanges(SaveChangesCompletedEventData eventData, int result)
    {
        var unitOfWork = provider.GetUnitOfWork();
        unitOfWork.BeginOrUseTransactionAsync().GetAwaiter().GetResult();
        return base.SavedChanges(eventData, result);
    }

    public override async ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result,
        CancellationToken cancellationToken = default)
    {
        var unitOfWork = provider.GetUnitOfWork();
        await unitOfWork.BeginOrUseTransactionAsync(cancellationToken);

        return await base.SavedChangesAsync(eventData, result, cancellationToken);
    }
}
